﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Nextensions.WinApi
{
    public class WindowFinder
    {
        private List<IntPtr> _matches = new List<IntPtr>();
        private List<IntPtr> _searched = new List<IntPtr>();

        public IntPtr[] FindRe(string WindowTextRegEx)
        {
            Win.EnumWindowsProc del = new Win.EnumWindowsProc(FindWindowProc);
            Win.EnumWindows(del, 0);

            Regex re = new Regex(WindowTextRegEx, RegexOptions.Compiled);

            for (int i = 0; i < _searched.Count; i++)
            {
                System.Text.StringBuilder text = new System.Text.StringBuilder(256);
                int res;
                res = Win.GetWindowText(_searched[i], text, text.Capacity);

                if (res > 0)
                {
                    if(re.IsMatch(text.ToString()))
                        _matches.Add(_searched[i]);
                }
            }

            return _matches.ToArray();
        }

        private bool FindWindowProc(IntPtr Handle, int lParam)
        {
            if (_searched.Contains(Handle))
                return false;

            _searched.Add(Handle);

            return true;
        }
    }
}
